package org.springblade.modules.notice.utils;

import org.springblade.modules.notice.enums.placeholder.VariableEnum;
import org.springblade.modules.notice.vo.CommonEnumInfo;

import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
 * @Author ysq
 * @Date 2024/11/27
 * @Description 业务变量工具类
 */
public class VariableUtil {

	public static <T extends VariableEnum> String getVarByCode(Integer code, Class<T> enumClass) {
		return Arrays.stream(enumClass.getEnumConstants())
			.filter(e -> Objects.equals(e.getCode(), code))
			.findFirst().map(VariableEnum::getVar).orElse("-");
	}

	public static <T extends VariableEnum> String getSqlByCode(Integer code, Class<T> enumClass) {
		return Arrays.stream(enumClass.getEnumConstants())
			.filter(e -> Objects.equals(e.getCode(), code))
			.findFirst().map(VariableEnum::getSql).orElse("");
	}

	public static <T extends VariableEnum> String getSqlByVar(String var, Class<T> enumClass) {
		return Arrays.stream(enumClass.getEnumConstants())
			.filter(e -> Objects.equals(e.getVar(), var))
			.findFirst().map(VariableEnum::getSql).orElse("");
	}

	public static <T extends VariableEnum> List<CommonEnumInfo> getSelectList(Class<T> enumClass) {
		if (enumClass == null) {
			return Collections.emptyList();
		}

		return Arrays.stream(enumClass.getEnumConstants())
			.filter(e -> e.getIsShow())
			.map(e -> new CommonEnumInfo(e.getCode(), String.format("%s: ${%s}", e.getDesc(), e.getVar())))
			.collect(Collectors.toList());
	}

	/**
	 * 提取${var}变量
	 * @param var
	 * @return
	 */
	public static Set<String> extractVariables(String var) {
		Set<String> vars = new LinkedHashSet<>();
		// 定义正则表达式
		Pattern pattern = Pattern.compile("\\$\\{([^}]*)\\}");
		Matcher matcher = pattern.matcher(var);

		while (matcher.find()) {
			vars.add(matcher.group(1));
		}
		return vars;
	}

	/**
	 * 提取${var}变量（只提取第一个）
	 */
	public static String extractVariable(String var) {
		return extractVariables(var).isEmpty() ? null : extractVariables(var).iterator().next();
	}

	/**
	 * 提取微信模板消息中的变量
	 * {{keyword1.DATA}} --> keyword1
	 * @param var
	 * @return
	 */
	public static String extractVariableWx(String var) {
		String pattern = "\\{\\{(\\w+)\\.DATA\\}\\}";
		Pattern r = Pattern.compile(pattern);
		Matcher m = r.matcher(var);
		if (m.find()) {
			return m.group(1);
		}
		return null;
	}
}
